﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using FacebookWrapper.ObjectModel;

namespace B12_Ex03_Eran_053094363_Assaf_036722999
{
    public class FriendWrapperForThreading
    {
        public string FriendPictureURL { get; set; }

        public string FriendTreeItem { get; set; }
        
        public Image FriendImage { get; private set; }

        public event EventHandler Finished;

        public bool IsFinished { get; private set; }

        public void GetFriendImage()
        {
            // Create an Asynchronous Image Object
            AsyncImageLoader asyncImage = new AsyncImageLoader();

            // Set the Image URL
            asyncImage.ImageURL = FriendPictureURL;

            // Run the Asynchronous Image Handler
            Thread thread = new Thread(new ThreadStart(asyncImage.GetImage));
            thread.Start();

            while (thread.ThreadState == ThreadState.Running)
            {
                // Check again before Sleeping - might already be stopped
                if (thread.ThreadState == ThreadState.Running)
                {
                    Thread.Sleep(1000);
                }
            }
            
            // Check if the returned Image is not null else Set the Default Facebook Picture
            FriendImage = asyncImage.ResultImage != null ? asyncImage.ResultImage : Properties.Resources.facebook_default;

            if (Finished != null)
            {
                Finished.Invoke(this, EventArgs.Empty);

                // Mark the Wrapper Thread as Finished
                IsFinished = true;
            }
        }        
    }
}
